package com.buba.config.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.buba.mapper.LgRoleMapper;
import com.buba.mapper.LgUserMapper;
import com.buba.mapper.LgUserRoleMapper;
import com.buba.pojo.LgRole;
import com.buba.pojo.LgUser;
import com.buba.pojo.LgUserRole;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

@Service
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private LgUserMapper lgUserMapper;
    @Autowired
    private LgUserRoleMapper lgUserRoleMapper;
    @Autowired
    private LgRoleMapper lgRoleMapper;
    @Getter
    private HashMap<String, Object> map = new HashMap<>();
    @Getter
    private UserDetails userDetails;

    @Override
    public UserDetails loadUserByUsername(String telephone) throws UsernameNotFoundException {
        QueryWrapper<LgUser> lgUserQueryWrapper = new QueryWrapper<>();
        LgUser lgUser = lgUserMapper.selectOne(lgUserQueryWrapper.lambda().eq(LgUser::getTelephone, telephone));
        if (lgUser == null) {
            throw new UsernameNotFoundException("用户名或密码不存在");
        }
        map.put("lgUser", lgUser);
        userDetails = new User(lgUser.getTelephone(), lgUser.getPassword(), getAuthorizations(lgUser));
        return userDetails;
    }

    private Collection<? extends GrantedAuthority> getAuthorizations(LgUser lgUser) {
        Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
        QueryWrapper<LgUserRole> lgUserRoleQueryWrapper = new QueryWrapper<>();
        LgUserRole lgUserRole = lgUserRoleMapper.selectOne(lgUserRoleQueryWrapper.lambda().eq(LgUserRole::getUserId, lgUser.getId()));
        LgRole lgRole = lgRoleMapper.selectById(lgUserRole.getRoleId());
        map.put("lgRole", lgRole);
        authorities.add(new SimpleGrantedAuthority("ROLE_" + lgRole.getRoleCode()));
        return authorities;
    }
}
